# -*- coding: utf-8 -*-
import logging
from pythonblog.model import meta
from pythonblog.model.navigation import Section, PostType
from sqlalchemy.sql import select

log = logging.getLogger(__name__)

_table = Section.__table__
_column = _table.c

_ptype_table = PostType.__table__
_ptype_column = _ptype_table.c

class SectionInfo(object):
    pass

class PostTypeInfo(object):
    pass

def _get_all_section_info():
    s = select([_column.id, _column.name, _column.path]).order_by(_column.id)
    sections = {}
    for id, name, path in meta.engine.execute(s).fetchall():
        sectionInfo = SectionInfo()
        sectionInfo.id = id
        sectionInfo.name = name
        sectionInfo.path = path
        sections[id] = sectionInfo
    return sections


def _get_all_post_type_info():
    s = select([_ptype_column.id, _ptype_column.name, _ptype_column.path]).order_by(_ptype_column.id)
    types = {}
    for id, name, path in meta.engine.execute(s).fetchall():
        type = PostTypeInfo()
        type.id = id
        type.name = name
        type.path = path
        types[id] = type
    return types

all_sections = _get_all_section_info()
all_types = _get_all_post_type_info()

#def get_all_section():
#    return meta.Session.query(Section).order_by(Section.id).all()

def get_section(id):
    return all_sections[id]

def get_section_by_path(path):
    for section in all_sections.values():
        if section.path == path:
            return section
    return None

def get_type(id):
    return all_types[id]

def get_type_by_path(path):
    for type in all_types.values():
        if type.path == path:
            return type
    return None

def get_title_by_path(path):
    if path == 'all':
        return u'全部'
    else:
        for section in all_sections.values():
            if section.path == path:
                return section.name

